{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Assess predictions on image classification fridge data with a pytorch model"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This notebook demonstrates the use of the `responsibleai` API to assess an image classification pytorch model trained on the fridge dataset. It walks through the API calls necessary to create a widget with model analysis insights, then guides a visual analysis of the model."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Launch Responsible AI Toolbox"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The following section examines the code necessary to create datasets and a model. It then generates insights using the `responsibleai` API that can be visually analyzed."
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Load Model and Data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import sys\n",
    "from zipfile import ZipFile\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import matplotlib\n",
    "matplotlib.use('Agg')\n",
    "import matplotlib.pyplot as plt\n",
    "from responsibleai_vision.common.constants import ImageColumns\n",
    "import json\n",
    "from fastai.learner import load_learner\n",
    "from raiutils.common.retries import retry_function\n",
    "\n",
    "try:\n",
    "    from urllib import urlretrieve\n",
    "except ImportError:\n",
    "    from urllib.request import urlretrieve\n",
    "\n",
    "EPOCHS = 10\n",
    "LEARNING_RATE = 1e-4\n",
    "IM_SIZE = 300\n",
    "BATCH_SIZE = 16\n",
    "FRIDGE_MODEL_NAME = 'fridge_model'\n",
    "FRIDGE_MODEL_WINDOWS_NAME = 'fridge_model_windows'\n",
    "WIN = 'win'\n",
    "\n",
    "def load_fridge_dataset():\n",
    "    # create data folder if it doesnt exist.\n",
    "    os.makedirs(\"data\", exist_ok=True)\n",
    "\n",
    "    # download data\n",
    "    download_url = (\"https://publictestdatasets.blob.core.windows.net/\" +\n",
    "                    \"computervision/fridgeObjects.zip\")\n",
    "    data_file = \"./data/fridgeObjects.zip\"\n",
    "    urlretrieve(download_url, filename=data_file)\n",
    "\n",
    "    # extract files\n",
    "    with ZipFile(data_file, \"r\") as zip:\n",
    "        print(\"extracting files...\")\n",
    "        zip.extractall(path=\"./data\")\n",
    "        print(\"done\")\n",
    "    # delete zip file\n",
    "    os.remove(data_file)\n",
    "    # get all file names into a pandas dataframe with the labels\n",
    "    data = pd.DataFrame(columns=[ImageColumns.IMAGE.value,\n",
    "                                 ImageColumns.LABEL.value])\n",
    "    \n",
    "    feats = []\n",
    "    for folder in os.listdir(\"./data/fridgeObjects\"):\n",
    "        for file in os.listdir(\"./data/fridgeObjects/\" + folder):\n",
    "            image_path = \"./data/fridgeObjects/\" + folder + \"/\" + file\n",
    "            feats.append({ImageColumns.IMAGE.value: image_path,\n",
    "                     ImageColumns.LABEL.value: folder})\n",
    "    \n",
    "    # get all file names into a pandas dataframe with the labels\n",
    "    data = pd.DataFrame(feats, columns=[ImageColumns.IMAGE.value,\n",
    "                                        ImageColumns.LABEL.value])\n",
    "\n",
    "    return data\n",
    "\n",
    "\n",
    "class FetchModel(object):\n",
    "    def __init__(self):\n",
    "        pass\n",
    "\n",
    "    def fetch(self):\n",
    "        if sys.platform.startswith(WIN):\n",
    "            model_name = FRIDGE_MODEL_WINDOWS_NAME\n",
    "        else:\n",
    "            model_name = FRIDGE_MODEL_NAME\n",
    "        url = ('https://publictestdatasets.blob.core.windows.net/models/' +\n",
    "               model_name)\n",
    "        urlretrieve(url, FRIDGE_MODEL_NAME)\n",
    "\n",
    "\n",
    "def retrieve_or_train_fridge_model(df, force_train=False):\n",
    "    if force_train:\n",
    "        model = train_fastai_image_classifier(df)\n",
    "        # Save model to disk\n",
    "        model.export(FRIDGE_MODEL_NAME)\n",
    "    else:\n",
    "        fetcher = FetchModel()\n",
    "        action_name = \"Dataset download\"\n",
    "        err_msg = \"Failed to download dataset\"\n",
    "        max_retries = 4\n",
    "        retry_delay = 60\n",
    "        retry_function(fetcher.fetch, action_name, err_msg,\n",
    "                       max_retries=max_retries,\n",
    "                       retry_delay=retry_delay)\n",
    "        model = load_learner(FRIDGE_MODEL_NAME)\n",
    "    return model"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Load Pretrained Faster RCNN model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data = load_fridge_dataset()\n",
    "model = retrieve_or_train_fridge_model(data)\n",
    "\n",
    "train_data = data\n",
    "test_data = data\n",
    "class_names = data[ImageColumns.LABEL.value].unique()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Create Model and Data Insights"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from raiwidgets import ResponsibleAIDashboard\n",
    "from responsibleai_vision import ModelTask, RAIVisionInsights"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To use Responsible AI Toolbox, initialize a RAIInsights object upon which different components can be loaded.\n",
    "\n",
    "RAIInsights accepts the model, the full dataset, the test dataset, the target feature string and the task type string as its arguments."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "rai_insights = RAIVisionInsights(model, test_data.sample(10, random_state=42),\n",
    "                                 \"label\",\n",
    "                                 task_type=ModelTask.IMAGE_CLASSIFICATION,\n",
    "                                 classes=class_names)\n",
    "\n",
    "rai_insights"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Add the components of the toolbox that are focused on model assessment."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Interpretability\n",
    "rai_insights.explainer.add()\n",
    "# Error Analysis\n",
    "rai_insights.error_analysis.add()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Once all the desired components have been loaded, compute insights on the test set."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "rai_insights.compute()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Finally, visualize and explore the model insights. Use the resulting widget or follow the link to view this in a new tab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ResponsibleAIDashboard(rai_insights)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "raivision",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.18"
  },
  "orig_nbformat": 4,
  "vscode": {
   "interpreter": {
    "hash": "053dc3c540a9260e9464092636530e4f43e21211e2a5bed21a6f6ec172233695"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
